package architect.springcloud.gateway.zuul.filter;

import architect.springcloud.gateway.zuul.constant.Constants;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 网关前置过滤器
 *
 * @author guanxin
 * @date 2018/4/22 21:03
 */

@Component
public class GatewayPreFilter extends ZuulFilter {

    @Autowired
    private Environment environment;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        System.out.println(ctx.getRequest().getSession().getId() + "  do something filter... " + ctx.getRequest().getMethod());
        String usernamepassword;
        try {
            //usernamepassword = environment.getProperty("");
            usernamepassword = Constants.DEFAULT_USERNAME_PASSWORD;
        } catch (Exception e) {
            usernamepassword = Constants.DEFAULT_USERNAME_PASSWORD;
            e.printStackTrace();
        }
        //添加Basic Auth认证信息，因为服务端开了认证
        ctx.addZuulRequestHeader("Authorization", "Basic " + getBase64Credentials(usernamepassword));

        return null;
    }

    private String getBase64Credentials(String usernamepassword) {
        byte[] plainCredsBytes = usernamepassword.getBytes();
        byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
        return new String(base64CredsBytes);
    }
}
